package com.my.study.globalfilter.normal;

import com.my.study.aop.annotation.FilterType;
import com.my.study.enums.ApiTypeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

import org.springframework.web.server.ServerWebExchange;

@Component
@Slf4j
public class RequestTimeGlobalFilter implements GlobalFilter, Ordered {

    @FilterType(type = ApiTypeEnum.NORMAL_API)
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        long startTime = System.currentTimeMillis();
        // 在请求被处理之前记录开始时间
        exchange.getAttributes().put("startTime", startTime);
        return chain.filter(exchange).then(
                Mono.fromRunnable(() -> {
                    long endTime = System.currentTimeMillis();
                    long duration = endTime - startTime;
                    log.info(exchange.getRequest().getURI() + ": " + duration + "ms");
                })
        );
    }

    @Override
    public int getOrder() {
        return -1;
    }
}
